const mongoose = require('mongoose');

const projectSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: [true, '项目标题是必填项'],
      trim: true,
      maxlength: [100, '项目标题不能超过100个字符'],
    },
    description: {
      type: String,
      trim: true,
      maxlength: [500, '项目描述不能超过500个字符'],
    },
    creator: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    collaborators: [
      {
        user: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User',
        },
        role: {
          type: String,
          enum: ['viewer', 'editor', 'admin'],
          default: 'viewer',
        },
        joinedAt: {
          type: Date,
          default: Date.now,
        },
      },
    ],
    content: {
      blocks: {
        type: Object,
        required: true,
      },
      sprites: [
        {
          id: String,
          name: String,
          scripts: [Object],
          costumes: [Object],
          position: {
            x: Number,
            y: Number,
          },
        },
      ],
      stage: {
        scripts: [Object],
        backgrounds: [Object],
        variables: [Object],
      },
    },
    thumbnail: {
      type: String,
      default: 'default-project-thumbnail.png',
    },
    isPublic: {
      type: Boolean,
      default: false,
    },
    tags: [String],
    category: {
      type: String,
      enum: ['游戏', '动画', '故事', '艺术', '音乐', '模拟', '教育', '其他'],
      default: '其他',
    },
    difficulty: {
      type: String,
      enum: ['初级', '中级', '高级'],
      default: '初级',
    },
    stats: {
      views: {
        type: Number,
        default: 0,
      },
      likes: {
        type: Number,
        default: 0,
      },
      forks: {
        type: Number,
        default: 0,
      },
      comments: {
        type: Number,
        default: 0,
      },
    },
    aiAssistance: {
      used: {
        type: Boolean,
        default: false,
      },
      suggestions: [
        {
          content: String,
          timestamp: Date,
          implemented: Boolean,
        },
      ],
    },
    version: {
      type: Number,
      default: 1,
    },
    history: [
      {
        version: Number,
        content: Object,
        updatedBy: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User',
        },
        timestamp: Date,
        comment: String,
      },
    ],
  },
  {
    timestamps: true,
  }
);

// 创建索引以提高查询性能
projectSchema.index({ creator: 1 });
projectSchema.index({ isPublic: 1 });
projectSchema.index({ tags: 1 });
projectSchema.index({ category: 1 });
projectSchema.index({ 'stats.views': -1 });
projectSchema.index({ 'stats.likes': -1 });
projectSchema.index({ createdAt: -1 });

const Project = mongoose.model('Project', projectSchema);

module.exports = Project;